import createRequest from './request';

export function gen(request, serverUrl, requestOptions) {
  let options = {};
  if (Object.prototype.toString.call(requestOptions) === '[object String]') {
    //拆分
    const optionsArray = requestOptions.split(' ');
    if (optionsArray.length === 2) {
      options.method = optionsArray[0];
      options.url = optionsArray[1];
    }
  } else if (Object.prototype.toString.call(requestOptions) === '[object Object]') {
    options = requestOptions;
  }

  if (!options.url.startsWith('https://') && !options.url.startsWith('http://')) {
    options.url = serverUrl + options.url;
  }

//数据提交格式
  return (data = {}) => {
    return request({
      ...options,
      data
    });
  };

}

export class ApiGenerator {

  constructor(serverUrl) {
    this.serverUrl = serverUrl;
    this.request = createRequest;
    this.genApi = this.genApi.bind(this);
  }

  genApi(apiList) {
    const API = {};
    if (Object.prototype.toString.call(apiList) === '[object Object]') {
      for (const key in apiList) {
        const api = apiList[key];
        API[key] = gen(this.request, this.serverUrl, api);
        API[key].isNewVersion = true; //区分老版本接口
      }
    }
    return API;
  }
}
